/*
 *  Copyright 2011 cubika.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.oilsoft.scm.dao.user;

import com.oilsoft.scm.dao.DAOImpl;
import com.oilsoft.scm.domain.User;
import java.util.List;
import javax.persistence.NonUniqueResultException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class UserDAOImpl extends DAOImpl<User> implements UserDAO {

    @Override
    @Transactional(readOnly=true)
    public User validateUser(String username, String password) {
        String query = "select u from User u where u.username = :username and u.password = :password";
        User loggedUser;
        try {
            loggedUser = (User) entityManager.createQuery(query).setParameter(
                    "username", username).setParameter("password",
                    password).getSingleResult();
        } catch (NonUniqueResultException e) {
            return loggedUser = null;
        } catch (Exception e) {
            return loggedUser = null;
        }
        return loggedUser;
    }

    @Override
    @Transactional(readOnly=true)
    public User getUser(String username) {
        String query = "select u from User u where u.username = :username";
        User user;
        try {
            user = (User) entityManager.createQuery(query).setParameter(
                    "username", username).getSingleResult();
        } catch (NonUniqueResultException e) {
            return user = null;
        } catch (Exception e) {
            return user = null;
        }
        return user;
    }

    @Override
    protected Class<User> getEntityClass() {
        return User.class;
    }

    @Override
    @Transactional(readOnly=true)
    public List<User> getAll() {
        String query = "select u from User u ";
        List<User> users =(List<User>) entityManager.createQuery(query).getResultList();
        return users;
    }
}
